package com.fywsy.fyweb.controller;

import com.fywsy.fyweb.entity.*;
import com.fywsy.fyweb.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/game")
public class GameController {

    @Autowired
    private GameRepository gameRepository;

    @Autowired
    CategoryRepository categoryRepository;

    @Autowired
    GamePicRepository gamePicRepository;

    @Autowired
    DownloadRepository downloadRepository;

    @Autowired
    GameLinkRepository gameLinkRepository;

    @Autowired
    ContactRepository contactRepository;

    /**
     * 游戏列表
     *
     * @return
     */
    @PostMapping("/list")
    public List<Game> getGames() {
        List<DownloadUrl> downloadUrls = downloadRepository.findAllByDeviceTypeAndVisable(11, true);
        Map<Long,String> urls = new HashMap<>();
        if(downloadUrls != null) {
            downloadUrls.stream().forEach(i-> {
                urls.put(i.gameId, i.link);
            });
        }
        List<Game> games = gameRepository.getAllByEnableAndVisableOrderByCreateTimeDesc(true, true);
        games.stream().forEach(i-> {
            i.downloadUrl = urls.get(i.id);
        });
        return games;
    }

    /**
     * 游戏列表
     * 提供给风云玩的接口
     *
     * @param free 稀有免费及不免费
     *             不再使用可以删除!
     * @return
     */
    @Deprecated
    @PostMapping("listByFree")
    public List<Game> getGamesByFree(boolean free) {
        List<Game> freeGames = gameRepository.getAllByEnableAndVisableAndExternalReadAndCateOrderByCreateTimeDesc(true, true, true, free ? 10 : 20);
        if(freeGames != null) {
            //因为createTime和对方类型不一样，所有这里处理下不返回给他
            freeGames.forEach(i-> i.createTime = null);
        }
        return freeGames;
    }

    /**
     * 通过分类获取游戏列表
     * 提供给风云玩使用
     * @param cate  游戏类型
     * @see com.fywsy.fyweb.utils.type.Cate
     * @return
     */
    @PostMapping("listByCate")
    public List<Game> getGamesByCate(int cate) {
        List<Game> freeGames = gameRepository.getAllByEnableAndVisableAndExternalReadAndCateOrderByCreateTimeDesc(true, true, true, cate);
        if(freeGames != null) {
            //因为createTime和对方类型不一样，所有这里处理下不返回给他
            freeGames.forEach(i-> {
                i.createTime = null;
                //买断游戏返回截图
                if(i.cate == 90) {
                    List<GamePic> pics = gamePicRepository.findAllByGameId(i.id);
                    if(pics != null && pics.size() > 0) {
                        i.pics = pics.stream().map(j-> j.url).collect(Collectors.toList());
                    }

                }
                //返回直链下载连接
                DownloadUrl downloadUrl = downloadRepository.getFirstByGameIdAndDeviceType(i.id, 11);
                if(downloadUrl != null) {
                    i.downloadUrl = downloadUrl.link;
                }
            });
        }
        return freeGames;
    }


    /**
     * 游戏详情
     *
     * @param params
     * @return
     */
    @PostMapping("/detail")
    public Game getDetail(@RequestBody RequestParams params) {
        Game game = gameRepository.findById(params.gameId).get();
        game.pics = gamePicRepository.findAllUrls(params.gameId);
        game.links = gameLinkRepository.findAllByEnableAndLocationAndGameId(true, 0, params.gameId);
        game.contacts = contactRepository.findAllByEnableAndGameId(true, params.gameId);
        return game;
    }

    /**
     * 获取简洁的game
     *
     * @param request
     * @return
     */
    @PostMapping("/getGameById")
    public Game getGameById(@RequestBody RequestParams request) {
        return gameRepository.findById(request.gameId).get();
    }

    /**
     * 按点击量倒叙排列类型
     * 先查全部游戏的tags
     * category不含的,就保存到category
     * 再按照category的views进行排序返回
     * @return
     */
    @PostMapping("/categories")
    public List<Category> getCategories() {
        // 获取所有游戏
        List<Game> games = gameRepository.getAllByEnableAndVisableOrderByCreateTimeDesc(true, true);
        
        // 收集所有标签并处理
        Set<String> allTags = new HashSet<>();
        for (Game game : games) {
            if (game.tags != null && !game.tags.isEmpty()) {
                // 替换中文逗号为英文逗号，然后分割
                String[] tags = game.tags.replace("，", ",").toLowerCase().split(",");
                for (String tag : tags) {
                    allTags.add(tag.trim());
                }
            }
        }
        
        // 获取所有现有分类
        List<Category> existingCategories = categoryRepository.findAll();
        Set<String> existingNames = existingCategories.stream()
                .map(category -> category.name.toLowerCase())
                .collect(Collectors.toSet());
        
        // 找出需要新增的分类
        Set<String> newTags = allTags.stream()
                .filter(tag -> !existingNames.contains(tag.toLowerCase()))
                .collect(Collectors.toSet());
        
        // 创建新的分类列表
        List<Category> newCategories = new ArrayList<>();
        for (String tag : newTags) {
            Category category = new Category();
            category.name = tag;
            category.views = 0;
            newCategories.add(category);
        }
        
        // 保存新的分类
        if (!newCategories.isEmpty()) {
            categoryRepository.saveAll(newCategories);
        }
        allTags.add("全部");
        // 返回从标签中提取的分类，并按点击量倒序排序
        return categoryRepository.findByNameInOrderByViewsDesc(allTags);
    }

    /**
     * game里面的tags 记录这个游戏的类型，tags包含了cate则返回
     *
     * @param params
     * @return
     */
    @PostMapping("/getGamesByCate")
    public List<Game> getGamesByCate(@RequestBody RequestParams params) {

        /**
         * 每次请求，views数量+1
         */
        Category currentCate = categoryRepository.findFirstByName(params.category);
        currentCate.views = currentCate.views + 1;
        categoryRepository.save(currentCate);

        //TODO 需要分页，不然读取太多图片
        List<Game> result;
        if (currentCate.id == 1) { //全部
            result = gameRepository.getAllByEnableAndVisableOrderByCreateTimeDesc(true, true);
        } else {
            result = gameRepository.findAllByEnableAndVisableAndTagsContaining(true, true, params.category);
        }
        result.forEach(i -> {
            i.pics = gamePicRepository.findUrls(i.id, i.landscape ? 1 : 3);
        });
        return result;
    }

    /**
     * 获取游戏下载地址
     *
     * @param params
     * @return
     */
    @PostMapping("/getDownloadUrls")
    public List<DownloadUrl> getDownloadUrls(@RequestBody RequestParams params) {
        return downloadRepository.findAllByVisableAndGameId(true, params.gameId);
    }

    @GetMapping("/search")
    public List<Game> search(String word) {
        List<Game> games = gameRepository.searchGames(word);
        games.forEach(game -> {
            game.pics = gamePicRepository.findUrls(game.id, game.landscape ? 1 : 3);
            game.createTime = null;
        });
        return games;
    }

}
